<template>
  <div class="fixed-table-actionbar">
    <div class="search-bar">
      <el-form :model="formItem" :inline="true" class="form-filter" size="mini">
        <el-form-item>
          <treeselect
            v-model="formItem.s_assetTypeCode"
            :multiple="false"
            :options="typeOptions"
            placeholder="选择资产类型"
            :disable-branch-nodes="true"
            @input="onOrgInput"
          />
        </el-form-item>
        <el-form-item>
          <el-select v-model="formItem.s_useDept" filterable clearable class="select_input" placeholder="请选择使用部门" @change="globalSearch">
            <el-option v-for="(item) in useDepts" :key="item.code" :label="item.text" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="formItem.s_submmitTo" filterable clearable class="select_input" placeholder="请选择移交单位" @change="globalSearch">
            <el-option v-for="(item) in dcomInstitutions" :key="item.name" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="formItem.s_globalSearch"
            placeholder="请输入查询内容..."
            clearable
            @keyup.enter.native="globalSearch"
            @change="onGlobeSearchInputChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button plain icon="el-icon-search" @click="globalSearch" />
        </el-form-item>
      </el-form>
    </div>
    <FormDialog title="导入" :show="uploadDialogFormVisible" width="40%" @on-ok="closeDialog" @on-cancel="closeDialog">
      <UploadNavigation v-if="uploadDialogFormVisible" :download-funct="template" file-name="资产导入模板" :upload-error="handleError" :action="importExcelurl" :upload-success="handleSuccess" />
    </FormDialog>
    <FormDialog
      class="fixed-dialog-height"
      title="新建"
      :show="dialogFormVisible"
      width="90%"
      @on-ok="ok"
      @on-cancel="cancel"
    >
      <EditForm ref="editForm" />
    </FormDialog>
    <ViewDialog
      :drawer="true"
      v-if="dialogViewVisibleForLifeCycle"
      class="fixed-dialog-height"
      title="生命周期履历"
      :show.sync="dialogViewVisibleForLifeCycle"
      width="90%"
      @on-cancel="dialogViewVisibleForLifeCycle = false"
    >
      <LifeCycleTable :asset="curAssetCode" />
    </ViewDialog>
  </div>
</template>

<script>
import treeselect from '@neu/biz-core/components/TreeSelect'
import { clone, isArray } from '@neu/biz-core/utils/utils'
import { exportExcel, importExcelUrl, template, scrap, qrcode, insititutions, lifeCycle } from '@neu/dcam-ui/api/fixedAsset'
import { getToken } from '@neu/biz-core/utils/auth'
import FormDialog from '@neu/biz-core/components/FormDialog'
import ViewDialog from '@neu/biz-core/components/ViewDialog'
import { tree } from '@neu/auth-ui/api/organization'
import UploadNavigation from '@neu/biz-core/components/UploadNavigation'
import * as assetType from '@neu/dcam-ui/api/assetType'
import { findByDictionaryType } from '@neu/dcam-ui/api/dictionary'
// 编辑实例组件独立编写，需要传递id属性，判断新建还是更新操作
import EditForm from './editForm'
import LifeCycleTable from './lifecycletables'
/** 全局检索key */
const formItem = {
  s_globalSearch: '',
  s_useDept: null,
  s_assetTypeCode: null,
  s_submmitTo: null
}
export default {
  name: 'FixedAssetActionBar',
  components: {
    FormDialog,
    ViewDialog,
    LifeCycleTable,
    EditForm,
    treeselect,
    UploadNavigation
  },
  props: {
    forSelection: {
      required: false,
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      /** 使用部门 */
      availableOganizations: [],
      uploadDialogFormVisible: false,
      /** 资产分类 */
      typeOptions: [],
      useDepts: [],
      formItem: clone(formItem),
      dialogFormVisible: false,
      importExcelurl: importExcelUrl,
      template: template,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Authentication': getToken()
      },
      dcomInstitutions: [],
      curAssetCode: '',
      dialogViewVisibleForLifeCycle: false
    }
  },
  created() {
    tree().then(response => {
      this.availableOganizations = [response.data]
    })
    assetType.tree().then(res => {
      this.typeOptions = res.data
    })
    findByDictionaryType('useDept').then(response => {
      this.useDepts = response.data
    })
    insititutions().then(response => {
      const dcomInstitutionsArray = response
      this.dcomInstitutions = []
      if (dcomInstitutionsArray) {
        dcomInstitutionsArray.forEach((data, index) => {
          this.dcomInstitutions.push(data)
        })
      }
    })
  },
  methods: {
    // 新建用户按钮点击处理
    add() {
      this.dialogFormVisible = true
    },
    // 创建用户对话框确认事件处理
    ok() {
      // 直接调用表单实例的保存方法
      this.$refs.editForm.save().then(response => {
        if (response === false) return
        this.$message({
          showClose: true,
          message: '操作成功！',
          type: 'success'
        })
        // 调用pageable-table实例的mixin方法refresh()，更新表格
        this.$parent.refresh()
        this.$refs.editForm.reset()
        // 关闭对话框
        this.dialogFormVisible = false
      })
    },
    cancel() {
      this.$refs.editForm.reset()
      this.dialogFormVisible = false
    },
    exportQrcode(ids) {
      qrcode(ids).then(res => {
        const content = res
        const blob = new Blob([content])
        const fileName = '二维码.pdf'
        if ('download' in document.createElement('a')) { // 非IE下载
          const elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
      })
    },
    lifeCyclePage(ids) {
      if (ids) {
        if (isArray(ids)) {
          const asset = ids[0]
          this.curAssetCode = asset.code
          this.dialogViewVisibleForLifeCycle = true
        }
      } else {
        this.$message({
          showClose: true,
          message: '请选择一条资产',
          type: 'error'
        })
      }
    },
    exportExcel() {
      const searchObj = this.$store.state.dcam.assetSearchObj
      console.log(searchObj)
      exportExcel(searchObj).then(res => {
        const content = res
        const blob = new Blob([content])
        const fileName = '导出信息.xlsx'
        if ('download' in document.createElement('a')) { // 非IE下载
          const elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
      })
    },
    handleBeforeUpLoad(file) {
      if (file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
        this.$message({
          showClose: true,
          message: '文件 ' + file.name + ' 格式不正确，请上传.xls,.xlsx文件。',
          type: 'error'
        })
      }
    },
    handleError(data) {
      this.$message({
        showClose: true,
        message: data,
        type: 'error'
      })
    },
    // vue treeselect 输入值改变事件
    onOrgInput(value) {
      this.globalSearch()
    },
    globalSearch() {
      this.$store.dispatch('dcam/setAssetSearchObj', this.formItem)
      // 清除另一个检索form表单
      if (this.$parent.$refs.filterForm) {
        this.$parent.$refs.filterForm.reset()
      }

      this.$parent.filter(this.formItem)
    },
    reset() {
      this.formItem = clone(formItem)
      this.globalSearch()
    },
    onGlobeSearchInputChange(value) {
      if (value === '') {
        this.globalSearch()
      }
    },
    clearForm() {
      this.formItem = clone(formItem)
    },
    qrcode(ids) {
      if (ids) {
        if (isArray(ids)) {
          if (ids.length > 1) {
            const idss = ids.map(it => it.id)
            this.exportQrcode(idss)
          } else if (ids.length === 1) {
            this.exportQrcode(ids[0].id)
          } else {
            this.$message({
              type: 'warning',
              message: '请选择操作数据!'
            })
            return
          }
        }
      } else {
        this.$message({
          showClose: true,
          message: '至少选择一条资产',
          type: 'error'
        })
      }
    },
    scrap(ids) {
      if (ids) {
        if (isArray(ids)) {
          if (ids.length > 1) {
            const idss = ids.map(it => it.id)
            this.$confirm(this.getConfirmContent(), '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              scrap(idss).then(response => {
                this.$message({
                  type: 'success',
                  message: '处置成功!'
                })
                this.$parent.refresh()
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消处置'
              })
            })
            return
          } else if (ids.length === 1) {
            const idArray = [ids[0].id]
            this.$confirm(this.getConfirmContent(), '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              scrap(idArray).then(response => {
                this.$message({
                  type: 'success',
                  message: '处置成功!'
                })
                this.$parent.refresh()
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消处置'
              })
            })
          } else {
            this.$message({
              type: 'warning',
              message: '请选择操作数据!'
            })
            return
          }
        }
      } else {
        this.$message({
          showClose: true,
          message: '至少选择一条资产',
          type: 'error'
        })
      }
    },
    lifeCycle(ids, status) {
      if (ids) {
        if (isArray(ids)) {
          if (ids.length > 1) {
            const idss = ids.map(it => it.id)
            this.$confirm('确认操作吗?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              lifeCycle(idss, status).then(response => {
                this.$message({
                  type: 'success',
                  message: '操作成功!'
                })
                this.$parent.refresh()
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消操作'
              })
            })
            return
          } else if (ids.length === 1) {
            const idArray = [ids[0].id]
            this.$confirm('确认操作吗?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              lifeCycle(idArray, status).then(response => {
                this.$message({
                  type: 'success',
                  message: '操作成功!'
                })
                this.$parent.refresh()
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消操作'
              })
            })
          } else {
            this.$message({
              type: 'warning',
              message: '请选择操作数据!'
            })
            return
          }
        }
      } else {
        this.$message({
          showClose: true,
          message: '至少选择一条资产',
          type: 'error'
        })
      }
    },
    // 页面可自定义确认文字
    getConfirmContent() {
      return '确定要处置吗？'
    },
    handleSuccess(response) {
      this.uploadDialogFormVisible = false
      this.$message({
        showClose: true,
        message: '资产导入为异步处理，请注意系统通知',
        type: 'success'
      })
      // this.$parent.refresh()
    },
    closeDialog() {
      this.uploadDialogFormVisible = false
      this.$parent.refresh()
    }
  }
}
</script>
